package cn.android666.net.util.download.apkdownload

import android.annotation.SuppressLint
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import cn.android666.net.util.download.dialog.DownloadDialog
import cn.android666.net.util.download.dialog.MyDialog
import timber.log.Timber

class ApkDownloadView(
    private val activity: AppCompatActivity,
    private val apkDownloadPresenter: ApkDownloadContract.Presenter,
    private val isForceUpdate: Boolean,
    /** 如果需要自己处理下载好的apk，则传此参数，如果传null，则默认会自动弹出安装对话框 */
    private val install: ((String) -> Unit)? = null) : ApkDownloadContract.View {

    private var downloadDialog: DownloadDialog? = null
    private var downloadDialogTag = "downloadDialog"

    override fun onPreDownload(apkName: String) {
        cancelDownloadDialog()

        val pauseButtonListener = View.OnClickListener {
            if (apkDownloadPresenter.isDownloading()) {
                apkDownloadPresenter.pauseDownload()
                downloadDialog?.setButtonText("开始下载")
            } else {
                apkDownloadPresenter.resumeDownload()
                downloadDialog?.setButtonText("暂停下载")
            }
        }

        val cancelButtonListener = View.OnClickListener {
            apkDownloadPresenter.pauseDownload()
            cancelDownloadDialog()
        }

        downloadDialog = DownloadDialog(apkName, isForceUpdate, pauseButtonListener, cancelButtonListener).also {
            it.show(activity.supportFragmentManager, downloadDialogTag)
        }
    }

    @SuppressLint("MissingPermission")
    override fun onDownloaded(filePath: String) {
        cancelDownloadDialog()
        MyDialog.Companion.show(activity, activity.supportFragmentManager, "tipDialog", {
            setTitle("提示")
            setMessage("应用之前就下载好了，是否直接安装?")
            setPositiveButton("重新下载") { _, _ -> apkDownloadPresenter.reDownload() }
            setNegativeButton("直接安装") { _, _ ->
                if (install == null) {
                    ApkUtil.install(activity, filePath)
                } else {
                    install(filePath)
                }
            }
            setCancelable(false)
        })
    }

    override fun onDownloadStart(fileDisplayName: String, fileSize: Long) {
        downloadDialog?.setMax(fileSize)
    }

    override fun onLoading(currentPosition: Long, speed: Long) {
        downloadDialog?.setProgress(currentPosition, speed)
    }

    @SuppressLint("MissingPermission")
    override fun onDownloadCompleted(fileSavedPath: String) {
        cancelDownloadDialog()
        if (install == null) {
            MyDialog.show(activity, activity.supportFragmentManager, "tipDialog", {
                setTitle("提示")
                setMessage("下载完成!")
                setPositiveButton("安装") { _, _ ->
                    ApkUtil.install(activity, fileSavedPath)
                }
                setCancelable(false)
            })
        } else {
            install(fileSavedPath)
        }
    }

    override fun onDownloadFail(errorMsg: String) {
        Timber.w(errorMsg)
        MyDialog.Companion.show(activity, activity.supportFragmentManager, "tipDialog", {
            setTitle("提示")
            setMessage(errorMsg)
            setPositiveButton("确定") { _, _ ->  }
            setCancelable(false)
        })
        cancelDownloadDialog()
    }

    private fun cancelDownloadDialog() {
        (activity.supportFragmentManager.findFragmentByTag(downloadDialogTag) as? DownloadDialog)?.dismissAllowingStateLoss()
    }

}